﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Web;
using System.Web.Mvc;
using III.Web.SaleDemo;

namespace ImageManageWeb.Controllers
{
    public class ImageManagerController : Controller
    {
        /// <summary>
        /// 保存图片
        /// </summary>
        public void SaveImage()
        {
            try
            {
                int paramSize = int.Parse(Request.Headers["ParamSize"].ToString());
                byte[] data = Request.BinaryRead(paramSize);
                //byte[] parambyte = data.Take(paramSize).ToArray();//其他参数
                //byte[] imgbyte = data.Skip(paramSize).ToArray();//图片
                ////拆分参数
                //var strData = Encoding.UTF8.GetString(parambyte).Split('&');
                //var dicData = new Dictionary<string, string>();
                //for (int i = 0; i < strData.Length; i++)
                //{
                //    var oneData = strData[i].Split('=');
                //    dicData[oneData[0]] = oneData[1];
                //}
                //var num = Convert.ToInt32(dicData["num"]);
                //var desc = dicData["desc"];

                //保存图片
                var path = "\\Upload\\LINGDAO\\" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "\\";
                var serverPath = Server.MapPath("~" + path);//图片路径
                if (!Directory.Exists(serverPath))
                {
                    Directory.CreateDirectory(serverPath);//创建文件夹
                }
                string fileName = Guid.NewGuid().ToString() + ".jpeg";
                DebugHelper.Info(serverPath + fileName);
                //图片流存储为图片文件
                MemoryStream ms = new MemoryStream(data, 0, data.Length);
                BinaryFormatter bf = new BinaryFormatter();
                object obj = bf.Deserialize(ms);
                ms.Close();
                var img=(Image)obj;
                img.Save(serverPath + fileName, ImageFormat.Jpeg);
                //MemoryStream ms = new MemoryStream(data);
                //Image image = Image.FromStream(ms);
                //image.Save(serverPath + fileName,ImageFormat.Jpeg);
                //DebugHelper.Info(serverPath + fileName);
                Response.HeaderEncoding = Encoding.UTF8;
                Response.Charset = "utf-8";
                Response.Write(path + fileName);
            }
            catch (Exception e)
            {
                DebugHelper.Info(e.Message);
                Response.HeaderEncoding = Encoding.UTF8;
                Response.Charset = "utf-8";
                Response.Write("error");
            }
        }

        public ActionResult Index()
        {
            return View();
        }
    }
}